switch statement in C#

The switch statement is a set of if statements it is a list of possibilities, which has an action for each possibility, and an alternate default action, if none evaluates the truth, then a simple switch description looks like this:


int number = 1;
switch(number)
{
    case 0:
        Console.WriteLine("The number is zero!");
        break;
    case 1:
        Console.WriteLine("The number is one!");
        break;
}

The identifier switch is placed after the keyword, and then there is a list of case details, where we check the identifier against a given value. You will see that at the end of each case we have a breakdown statement. Before the end of C #, we need to leave the block if you were writing the function, then you can use the return statement instead of a break statement.

In this case, we use an integer, but it can also be a string or some other ordinary type. In addition, you can specify the same action for multiple cases. We will also do this in the next example, where we take a piece from the user and use it in our switch statement:


Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
    case "yes":
    case "maybe":
        Console.WriteLine("Great!");
        break;
    case "no":
        Console.WriteLine("Too bad!");
        break;
}

In this example, we ask the user a question, and suggest that they do yes, or maybe we enter user input, and make a switch statement for it. To help the user, we change the lowercase before checking against the input against our lowercase string so that there is no difference between lowercase and uppercase letters.

However, the user can try to write something typo or completely, and in that case, this specific switch description will not produce any specific output. Enter the default keyword!


Console.WriteLine("Do you enjoy C# ? (yes/no/maybe)");
string input = Console.ReadLine();
switch(input.ToLower())
{
    case "yes":
    case "maybe":
        Console.WriteLine("Great!");
        break;
    case "no":
        Console.WriteLine("Too bad!");
        break;
    default:
        Console.WriteLine("I'm sorry, I don't understand that!");
        break;
}

If any case does not evaluate the statement on the right then the default statement, if any, will be executed. This is optional, as we saw in previous examples.